﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

public class CustomColorComboBox : ComboBox
{
    // 自定义颜色属性
    [Category("外观")]
    [Description("下拉列表项的背景颜色")]
    public Color ItemBackColor { get; set; } = Color.White;

    [Category("外观")]
    [Description("下拉列表项的文字颜色")]
    public Color ItemForeColor { get; set; } = Color.Black;

    [Category("外观")]
    [Description("选中项的背景颜色")]
    public Color SelectedItemBackColor { get; set; } = Color.RoyalBlue;

    [Category("外观")]
    [Description("选中项的文字颜色")]
    public Color SelectedItemForeColor { get; set; } = Color.White;

    [Category("外观")]
    [Description("下拉列表的背景颜色")]
    public Color DropDownBackColor { get; set; } = SystemColors.Control;

    public CustomColorComboBox()
    {
        // 设置为DropDownList风格
        DropDownStyle = ComboBoxStyle.DropDownList;
        // 设置为所有者绘制模式
        DrawMode = DrawMode.OwnerDrawFixed;
        // 启用双缓冲减少闪烁
        DoubleBuffered = true;
    }

    // 重绘下拉项
    protected override void OnDrawItem(DrawItemEventArgs e)
    {
        // 绘制背景
        e.DrawBackground();

        // 检查项索引是否有效
        if (e.Index >= 0 && e.Index < Items.Count)
        {
            // 获取当前项
            string itemText = Items[e.Index].ToString();

            // 设置颜色
            Color backColor = (e.State & DrawItemState.Selected) != 0
                ? SelectedItemBackColor
                : ItemBackColor;

            Color foreColor = (e.State & DrawItemState.Selected) != 0
                ? SelectedItemForeColor
                : ItemForeColor;

            // 绘制项背景
            using (SolidBrush brush = new SolidBrush(backColor))
            {
                e.Graphics.FillRectangle(brush, e.Bounds);
            }

            // 绘制项文本
            using (SolidBrush brush = new SolidBrush(foreColor))
            {
                // 调整文本位置，避免被截断
                Rectangle textRect = new Rectangle(
                    e.Bounds.X + 2,
                    e.Bounds.Y + 2,
                    e.Bounds.Width - 4,
                    e.Bounds.Height - 4
                );

                e.Graphics.DrawString(
                    itemText,
                    e.Font,
                    brush,
                    textRect,
                    StringFormat.GenericDefault
                );
            }
        }

        // 绘制焦点框
        e.DrawFocusRectangle();
    }

    // 重绘下拉列表背景
    protected override void WndProc(ref Message m)
    {
        const int WM_CTLCOLORLISTBOX = 0x0134;

        // 处理下拉列表背景绘制消息
        if (m.Msg == WM_CTLCOLORLISTBOX)
        {
            // 设置下拉列表背景色
            using (SolidBrush brush = new SolidBrush(DropDownBackColor))
            {
               // m.Result = (IntPtr)brush.Handle;
            }
            return;
        }

        base.WndProc(ref m);
    }
}
